<template>
  <div>
    <i class="wyicon-diqiu" @click="clickMapSource"></i>
<!--    <div class="layer-tip hidden">
      <div class="tip-title">图层</div>
      <div class="tip-right-arrow"></div>
    </div>-->
    <div class="layer-popup" v-show="showThisVue">
      <div v-for="(item,index) in config.mapDataTypeData"
           :id="item.f_id"
           class='layer-icon'
           :type="item.f_ename"
           :key="item.f_id"
           @click="switchLayer(item.f_id)">
        <div class='layer-popup-title'>{{ item.f_name }}</div>
      </div>
    </div>
  </div>
</template>

<script>
//import gConfig from "@/assets/js/GlobalConfig";
import globalmf from "@/utils/Global/GlobalMapFunction";
import axios from 'axios';
import {getMapSourceList, getMapSourceListByMapTypeId} from "@/api/portal/mapSource";
import {getCatalogQueryConfigListById} from "@/api/portal/catalog";

export default {
  name: "mapSource",
  data() {
    return {
      showThisVue: false,//初始不显示
      renderTable: null,
      selectedProtalRoles: null,
      selectedDataTypeNode: null,
      selectServiceType: null,
      selectPrjType: null,
      mapsOrigin: [], //初始地图
      prj: null,
      prjCode: "4490",
      prjCodeStr: "EPSG:4490", //"EPSG:4490",
      sort: [],
      config: {
        //目录数据
        "mapSourceData": [],
        //目录树数据，只有目录节点
        "mapDataTypeData": [],
        //数据类型
        "serviceType": [],
        //投影类型
        "prjType": [],
        //当前选择类型的地图数据
        "mapDataSelected": [],
        "alreadyDone": false,
      },
      aLDmapSourceData: false,
      aLDallLayers: false,
      allLayerNum: 0,
      selectLayInformation: null,//注记图层
      overSourceDsZj: null,//地市注记的overSource
      overSourceXjZj: null,//县级注记的overSource
      overSourceXzjZj: null,//乡镇级注记的overSource
      overSourceCjZj: null,//村级注记的overSource
      clusterSourceCjZj: null,//村级聚合Cluster
    }
  },
  props: {
    map: {
      type: Object,
      default() {
        return {}
      }
    },
  },
  created() {
    this.init();
  },
  mounted() {
  },
  watch: {
    aLDmapSourceData(newValue, oldValue) {//从后台读取了所有地图图层配置信息
      if (newValue === true) {
        this.initLayer();//第二步
      }
    },
    aLDallLayers(newValue, oldValue) {//已获取了所有图层
      let that = this;
      if (newValue === true) {//第三步
        globalmf.loadMapServices(that.map, that.config.mapSourceData, 0);
      }
    },
  },
  methods: {
    /**
     * @method init
     * 初始化
     */
    init: function (option) {
      var that = this;
      that.allLayerNum = 0;//应该加载的图层。
      //type 0是普通图层，1表示注记

      that.queryMapSourceAjax();//第一步
//增加地市注记
      globalmf.createLayerEasy(that.map, "XZQ_DSJ_pointZJ", 'XZQ_DSJ_pointZJ', 1, 10000);
      globalmf.createLayerEasy(that.map, "XZQ_XJ_pointZJ", 'XZQ_XJ_pointZJ', 1, 10000);
      globalmf.createLayerEasy(that.map, "XZQ_XZJ_pointZJ", 'XZQ_XZJ_pointZJ', 1, 10000);
      //createLayerEasy2固定死了样式。不在挨个修改feature的style
      let cjtextConfig = {
        font: 'bold 14px sans-serif', // 设置字体
        // maxAngle: 30,
        // offsetx: 10, // 设置文字偏移量
        // offsetY: 10,
        fill: new ol.style.Fill({
          // 字体颜色
          color: '#fffffc',
        }),
        stroke: new ol.style.Stroke({
          // 文字描边
          color: '#434343',
          width: 3,
        }),
      }
      //村级加载太慢，先不加入了
      //globalmf.createLayerEasy2(that.map, "XZQ_CJ_pointZJ", 'XZQ_CJ_pointZJ', 1, 10000,cjtextConfig);
      //2022年8月29日 lQ 想用Cluster解决注记过密的问题，没有成功。算了，先不管
   //   globalmf.createClusterLayer(that.map, "XZQ_CJ_pointZJ", 'XZQ_CJ_pointZJ', 1, 10000, this.clusterSourceCjZj);
      that.addXZQPointLayer();//先增加地市的标注

    },

    clickMapSource() {
      this.showThisVue = !this.showThisVue;
    },
    /*
     * 界面初始化
     * @return {undefined}
     */
    initLayer() {
      let that = this;
      //初始地图
      let resolutions = [];
      for (let zoom = 0; zoom < 22; zoom++) {
        resolutions.push(topResolution / Math.pow(2, zoom));
      }
      let topResolution = 360.0 / 512;
      //(that.prjCodeStr, "+proj=longlat +ellps=GRS80 +no_defs");
      //proj4.defs("EPSG:4490", "+proj=longlat +ellps=GRS80 +no_defs");
      that.prj = ol.proj.get(that.prjCodeStr);
      let envelope = {};
      envelope.left = -180;
      envelope.bottom = -90;
      envelope.right = 180;
      envelope.top = 90;
      that.prj.setExtent([envelope.left, envelope.bottom, envelope.right, envelope.top]);
      that.prj.setWorldExtent([envelope.left, envelope.bottom, envelope.right, envelope.top]);
      let origin = [envelope.left, envelope.top];
      let tileGrid = new ol.tilegrid.TileGrid({
        resolutions: resolutions,
        origin: origin,
        tileSize: 512
      });
      for (let i in that.config.mapSourceData) {
        let map = that.config.mapSourceData[i];
        if (map.f_servicetype === 1) {
          let basicRESTLayer = new ol.layer.Tile({
            source: new ol.source.TileSuperMapRest({
              url: map.f_url,
              wrapX: true,
              crossOrigin: "anonymous",
              tileGrid: tileGrid
            }),
            projection: that.prj,
            name: map.f_name,
            id: map.f_id,
            type: 0,
            sort: map.f_sort,
          });
          if (map.f_islabel == 1) {
            basicRESTLayer.setZIndex(9999);
          }
          if (map.f_zmin) {
            basicRESTLayer.setMinZoom(map.f_zmin);
          }
          if (map.f_zmax) {
            basicRESTLayer.setMaxZoom(map.f_zmax);
          }
          that.mapsOrigin.push(basicRESTLayer);
          if (that.allLayerNum === that.config.mapSourceData.length) {
            that.aLDallLayers = true;
          }
          that.sort.push(map.f_sort);
        } else if (map.f_servicetype === 3 || map.f_servicetype === 4) {//加载wmts服务
          if (map.f_sys === 4490) {
            let basicWMTSLayer = that.AddWMTS4490Layer(map);
          }
        } else if (map.f_servicetype === 7) {//加载天地图wmts服务
          that.AddTDTWMTSService(map);
        }
      }

    },
    /*
     * 界面初始化
     * @return {undefined}
     */
    initUI: function () {
      let that = this;
      that.sort.reverse();
      for (var i in that.mapsOrigin) {
        var layer = that.mapsOrigin[i];
        if (layer.getZIndex() != 9999) {
          layer.setZIndex(that.sort[i]);
        }
      }
    },
    //切换底图
    switchLayer(layerId) {//这个还是先同步吧
      let that = this;
      getMapSourceListByMapTypeId(layerId).then(function (res) {
        that.config.mapDataSelected = res.data.mapData;//2022年3月5日 LQ。现在SpringBoot返回的直接是一个数组，不是json串了。
        globalmf.loadMapServices(that.map, that.config.mapDataSelected, 0);
      }).catch(res => {
        console.log("发送失败" + resp.status + "," + resp.statusText);
      });
    },
    /*
     * 查询底图资源目录
     * @param {type} param 参数
     * @return {jqXHR}
     */
    queryMapSourceAjax(param) {
      let that = this;
      getMapSourceList().then(function (res) {
        that.config.mapSourceData = res.data.mapSourceData;
        that.config.mapDataTypeData = res.data.mapTypeData;
        that.aLDallLayers = true;
      }).catch(res => {
        console.log("发送失败" + res.status + "," + res.statusText);
      });
    },
    //增加一个vector的注记层
    addXZQPointLayer() {
      let that = this;

      //想用cluster,配置村级注记layer,失败
      /*
      if (that.overSourceCjZj) {
        that.overSourceCjZj.clear();
      } else {
        that.overSourceCjZj = new ol.source.Vector({
          // features: features,
          crossOrigin: 'anonymous',
          wrapX: false
        })
        //cluster
        that.clusterSourceCjZj = new ol.source.Cluster({
          distance: 1,
          source: that.overSourceCjZj
        });
      }
*/

      let layerDSJ = globalmf.getLayerByName(that.map, "XZQ_DSJ_pointZJ");
      let layerXJ = globalmf.getLayerByName(that.map, "XZQ_XJ_pointZJ");
      let layerXZJ = globalmf.getLayerByName(that.map, "XZQ_XZJ_pointZJ");
     // 2022年10月12日 LQ 先去掉村级
      let layerCJ = globalmf.getLayerByName(that.map, "XZQ_CJ_pointZJ");

      //配置地市注记layer
      if (that.overSourceDsZj) {
        that.overSourceDsZj.clear();
      } else {
        that.overSourceDsZj = new ol.source.Vector({
          // features: features,
          crossOrigin: 'anonymous',
          wrapX: false
        })
      }
      layerDSJ.setSource(that.overSourceDsZj);
      //配置县注记layer
      if (that.overSourceXjZj) {
        that.overSourceXjZj.clear();
      } else {
        that.overSourceXjZj = new ol.source.Vector({
          // features: features,
          crossOrigin: 'anonymous',
          wrapX: false
        })
      }
      layerXJ.setSource(that.overSourceXjZj);
      //配置乡镇注记layer
      if (that.overSourceXzjZj) {
        that.overSourceXzjZj.clear();
      } else {
        that.overSourceXzjZj = new ol.source.Vector({
          // features: features,
          crossOrigin: 'anonymous',
          wrapX: false
        })
      }
      layerXZJ.setSource(that.overSourceXzjZj);

      //配置村级注记layer
      if (that.overSourceCjZj) {
        that.overSourceCjZj.clear();
      } else {
        that.overSourceCjZj = new ol.source.Vector({
          // features: features,
          crossOrigin: 'anonymous',
          wrapX: false
        })
      }
      if(layerCJ){
      layerCJ.setSource(that.overSourceCjZj);
      }
      let layerDSJId = "3028e17a-6a18-461d-94eb-4d9f1498410b";//地市级注记的ID
      let layerXJId = "377b4503-30b1-4e34-89ce-6351e115596a";//县级注记的ID
      let layerXZJId = "434402d3-d7a9-4a0c-86c0-463fcec0e59a";//乡镇注记的ID
      //let layerCJId = "71d86b3a-2b54-4f72-8fa8-e86158164643";//村注记的ID
      let layerCJId ="-1";
        axios.all([
          getCatalogQueryConfigListById({"serviceId":layerDSJId}),
        getCatalogQueryConfigListById({"serviceId":layerXJId}),
        getCatalogQueryConfigListById({"serviceId":layerXZJId}),
        getCatalogQueryConfigListById({"serviceId":layerCJId})
      ]).then(axios.spread(function (resDSJ, resXJ, resXZJ, resCJ) {
                if (resDSJ.data.queryData.length > 0) {
                  let obj = resDSJ.data.queryData[0];
                  let name = obj.f_name;
                  let dataUrl = obj.f_url; //数据服务地址
                  let analysisUrl = obj.f_analysisurl; //分析服务地址
                  let datasourceNames = [{"name": obj.f_datasource, "value": obj.f_datasource}];
                  let datasetNames = [{"name": obj.f_dataset, "value": obj.f_dataset}];
                  let fieldData = JSON.parse(obj.f_fieldconfig);
                  if (analysisUrl != null && analysisUrl != "") {
                    let layerjson = {
                      "name": name,
                      "id": layerDSJId,
                      "dataUrl": dataUrl,
                      "analysisUrl": analysisUrl,
                      "datasourceName": datasourceNames[0].name,
                      "datasetName": datasetNames[0].name,
                      "fieldData": fieldData,
                      zmin: obj.zmin,
                      zmax: obj.zmax,
                    };
                    if (layerjson.zmin) {
                      layerDSJ.setMinZoom(layerjson.zmin)
                    }
                    if (layerjson.zmax) {
                      layerDSJ.setMaxZoom(layerjson.zmax)
                    }
                    // that.selectLayInformation = layerjson;
                    let dsjtextConfig = {
                      font: 'bold 16px sans-serif', // 设置字体
                      // maxAngle: 30,
                      // offsetx: 10, // 设置文字偏移量
                      // offsetY: 10,
                      fill: new ol.style.Fill({
                        // 字体颜色
                        color: '#eefcf8',
                      }),
                      stroke: new ol.style.Stroke({
                        // 文字描边
                        color: '#434343',
                        width: 2,
                      }),
                    }
                    that.queryFeaturesByRegionsAjax(layerjson, that.overSourceDsZj, dsjtextConfig,1);
                  }
                }
                if (resXJ.data.queryData.length > 0) {
                  let objXJ = resXJ.data.queryData[0];
                  let name = objXJ.f_name;
                  let dataUrl = objXJ.f_url; //数据服务地址
                  let analysisUrl = objXJ.f_analysisurl; //分析服务地址
                  let datasourceNames = [{"name": objXJ.f_datasource, "value": objXJ.f_datasource}];
                  let datasetNames = [{"name": objXJ.f_dataset, "value": objXJ.f_dataset}];
                  let fieldData = JSON.parse(objXJ.f_fieldconfig);
                  if (analysisUrl != null && analysisUrl != "") {
                    let xjlayerjson = {
                      "name": name,
                      "id": layerXJId,
                      "dataUrl": dataUrl,
                      "analysisUrl": analysisUrl,
                      "datasourceName": datasourceNames[0].name,
                      "datasetName": datasetNames[0].name,
                      "fieldData": fieldData,
                      zmin: objXJ.zmin,
                      zmax: objXJ.zmax,
                    };

                    if (xjlayerjson.zmin) {
                      layerXJ.setMinZoom(xjlayerjson.zmin)
                    }
                    if (xjlayerjson.zmax) {
                      layerXJ.setMaxZoom(xjlayerjson.zmax)
                    }
                    // that.selectLayInformation = layerjson;
                    let xjtextConfig = {
                      font: 'bold 18px sans-serif', // 设置字体
                      // maxAngle: 30,
                      // offsetx: 10, // 设置文字偏移量
                      // offsetY: 10,
                      fill: new ol.style.Fill({
                        // 字体颜色
                        color: '#f9f97b',
                      }),
                      stroke: new ol.style.Stroke({
                        // 文字描边
                        color: '#434343',
                        width: 2,
                      }),
                    }
                    that.queryFeaturesByRegionsAjax(xjlayerjson, that.overSourceXjZj, xjtextConfig,1);
                  }
                }
                if (resXZJ.data.queryData.length > 0) {
                  let objXZJ = resXZJ.data.queryData[0];
                  let name = objXZJ.f_name;
                  let dataUrl = objXZJ.f_url; //数据服务地址
                  let analysisUrl = objXZJ.f_analysisurl; //分析服务地址
                  let datasourceNames = [{"name": objXZJ.f_datasource, "value": objXZJ.f_datasource}];
                  let datasetNames = [{"name": objXZJ.f_dataset, "value": objXZJ.f_dataset}];
                  let fieldData = JSON.parse(objXZJ.f_fieldconfig);
                  if (analysisUrl != null && analysisUrl != "") {
                    let xzjlayerjson = {
                      "name": name,
                      "id": layerXZJId,
                      "dataUrl": dataUrl,
                      "analysisUrl": analysisUrl,
                      "datasourceName": datasourceNames[0].name,
                      "datasetName": datasetNames[0].name,
                      "fieldData": fieldData,
                      zmin: objXZJ.zmin,
                      zmax: objXZJ.zmax,
                    };

                    if (xzjlayerjson.zmin) {
                      layerXZJ.setMinZoom(xzjlayerjson.zmin)
                    }
                    if (xzjlayerjson.zmax) {
                      layerXZJ.setMaxZoom(xzjlayerjson.zmax)
                    }
                    // that.selectLayInformation = layerjson;
                    let xzjtextConfig = {
                      font: 'bold 16px sans-serif', // 设置字体
                      // maxAngle: 30,
                      // offsetx: 10, // 设置文字偏移量
                      // offsetY: 10,
                      fill: new ol.style.Fill({
                        // 字体颜色
                        color: '#ffffd6',
                      }),
                      stroke: new ol.style.Stroke({
                        // 文字描边
                        color: '#434343',
                        width: 2,
                      }),
                    }
                    that.queryFeaturesByRegionsAjax(xzjlayerjson, that.overSourceXzjZj, xzjtextConfig,1);
                  }
                }
                if (resCJ.data.queryData.length > 0) {
                  let objCJ = resCJ.data.queryData[0];
                  let name = objCJ.f_name;
                  let dataUrl = objCJ.f_url; //数据服务地址
                  let analysisUrl = objCJ.f_analysisurl; //分析服务地址
                  let datasourceNames = [{"name": objCJ.f_datasource, "value": objCJ.f_datasource}];
                  let datasetNames = [{"name": objCJ.f_dataset, "value": objCJ.f_dataset}];
                  let fieldData = JSON.parse(objCJ.f_fieldconfig);
                  if (analysisUrl != null && analysisUrl != "") {
                    let cjlayerjson = {
                      "name": name,
                      "id": layerCJId,
                      "dataUrl": dataUrl,
                      "analysisUrl": analysisUrl,
                      "datasourceName": datasourceNames[0].name,
                      "datasetName": datasetNames[0].name,
                      "fieldData": fieldData,
                      zmin: objCJ.zmin,
                      zmax: objCJ.zmax,
                    };

                    if (cjlayerjson.zmin) {
                      layerCJ.setMinZoom(cjlayerjson.zmin)
                    }
                    if (cjlayerjson.zmax) {
                      layerCJ.setMaxZoom(cjlayerjson.zmax)
                    }
                    // that.selectLayInformation = layerjson;
                    let cjtextConfig = {
                      font: 'bold 14px sans-serif', // 设置字体
                      // maxAngle: 30,
                      // offsetx: 10, // 设置文字偏移量
                      // offsetY: 10,
                      fill: new ol.style.Fill({
                        // 字体颜色
                        color: '#fffffc',
                      }),
                      stroke: new ol.style.Stroke({
                        // 文字描边
                        color: '#434343',
                        width: 3,
                      }),
                    }
                   // that.queryFeaturesByRegionsAjax(cjlayerjson, that.overSourceCjZj, cjtextConfig,1);
                    that.queryFeaturesByRegionsAjax2(cjlayerjson, that.overSourceCjZj, cjtextConfig,1);
                  }
                }
              })
          );


    },
    //查询要素并显示
    //renewStyle之前想用一下cluster。但是有问题，没解决，先不管了。
    queryFeaturesByRegionsAjax(layerjson, theoverSource, textConfig, renewStyle) {
      //sql查询
      let that = this;
      let attributeFilter = "";
      let sqlParam = new SuperMap.GetFeaturesBySQLParameters({
        queryParameter: {
          name: layerjson.datasetName + "&" + layerjson.datasourceName,
          //attributeFilter: that.sqlStr,
          attributeFilter: attributeFilter,
        },
        datasetNames: [layerjson.datasourceName + ":" + layerjson.datasetName],
        fromIndex: 0,
        toIndex: -1,
        maxFeatures: -1//不加上这一句，就只返回最多1000条结果
      });
      new ol.supermap.FeatureService(layerjson.dataUrl).getFeaturesBySQL(sqlParam, function (serviceResult) {
        // that.attribute.totalCount = serviceResult.result.totalCount;
        let features = (new ol.format.GeoJSON()).readFeatures(serviceResult.result.features);
        if (features.length > 0) {
          for (let i = 0; i < features.length; i++) {
            let xzqmc = features[i].get("XZQMC".toUpperCase());
            if (renewStyle.toString() === "1") {
              let zjstyle = new ol.style.Style({
                text: new ol.style.Text({
                  textAlign: 'center',     //对齐方式
                  textBaseline: 'middle',    //文本基线
                  font: textConfig.font, // 设置字体
                  // maxAngle: 30,
                  // offsetx: 10, // 设置文字偏移量
                  // offsetY: 10,
                  text: xzqmc, // 文字描述
                  fill: textConfig.fill,
                  stroke: textConfig.stroke,
                  // backgroundFill: new ol.style.Fill({      // 填充背景
                  //   color:'rgba(163,224,210,0.6)',
                  // }),
                }),
              })
              features[i].setStyle(zjstyle);
            }
            theoverSource.addFeature(features[i]);
          }


          //why20211018转换投影
          // let defaultPrjCode = that.sqlConfig.mapRegion.prjcode;
          // let mapPrjCode = that.sqlConfig.map.getView().getProjection().getCode();
          // if (defaultPrjCode != mapPrjCode) {
          //   for (let i = 0; i < features.length; i++) {
          //     features[i].getGeometry().transform(that.prj, that.map.getView().getProjection().getCode());
          //   }
          // }

        }
      });
    },
    //查询要素并显示
    //renewStyle之前想用一下cluster。但是有问题，没解决，先不管了。
    queryFeaturesByRegionsAjax2(layerjson, theoverSource, textConfig, renewStyle) {
      //sql查询
      let that = this;
      let attributeFilter = "";
      let sqlParam = new SuperMap.GetFeaturesBySQLParameters({
        queryParameter: {
          name: layerjson.datasetName + "&" + layerjson.datasourceName,
          //attributeFilter: that.sqlStr,
          attributeFilter: attributeFilter,
        },
        datasetNames: [layerjson.datasourceName + ":" + layerjson.datasetName],
        fromIndex: 0,
        toIndex: -1,
        maxFeatures: -1//不加上这一句，就只返回最多1000条结果
      });
      new ol.supermap.FeatureService(layerjson.dataUrl).getFeaturesBySQL(sqlParam, function (serviceResult) {
        // that.attribute.totalCount = serviceResult.result.totalCount;
        let features = (new ol.format.GeoJSON()).readFeatures(serviceResult.result.features);
        if (features.length > 0) {
          // for (let i = 0; i < features.length; i++) {
          //   let xzqmc = features[i].get("XZQMC".toUpperCase());
          //     features[i].setStyle(zjstyle);
          // }
          theoverSource.addFeatures(features);

          //why20211018转换投影
          // let defaultPrjCode = that.sqlConfig.mapRegion.prjcode;
          // let mapPrjCode = that.sqlConfig.map.getView().getProjection().getCode();
          // if (defaultPrjCode != mapPrjCode) {
          //   for (let i = 0; i < features.length; i++) {
          //     features[i].getGeometry().transform(that.prj, that.map.getView().getProjection().getCode());
          //   }
          // }

        }
      });
    },
  },

}
</script>

<style scoped>
.layer-tip, .layer-popup {
  position: absolute;
  font-size: 11px;
  border-radius: 3px;
  z-index: 2;
}

.layer-tip {
  left: -55px;
  top: 3px;
  background-color: rgba(0, 60, 136, .5);
  width: 50px;
  height: 25px;
}

i {
  cursor: pointer;
  /*background-color: rgba(0, 60, 136, .5);*/
  width: 25px;
  height: 25px;
  border-radius: 4px;
  display: inline;
  padding: 4px;
  color: #ffffffeb;
}

.layer-popup {
  /*left: -282px;width: 276px; */
  right: 30px;
  top: -30px;
  background-color: rgba(255, 255, 255, .5);
  width: auto;
  height: 92px;
  display: inline-flex;
}

.layer-popup .layer-icon {
  position: relative;
  float: left;
  width: 80px;
  height: 80px;
  margin: 5px;
  display: block;
  border: 1px solid #838383;
  cursor: pointer;
}

.layer-popup .layer-icon[type=vector] {
  background: url(~@/assets/images/basemap/vec_c.png) no-repeat center;
}

.layer-popup .layer-icon[type=image] {
  background: url(~@/assets/images/basemap/img_c.png) no-repeat center;
}

.layer-popup .layer-icon[type=terrain] {
  background: url(~@/assets/images/basemap/ter_c.png) no-repeat center;
}

.layer-popup .layer-icon[type=dark] {
  background: url(~@/assets/images/basemap/blackbluechina_c.png) no-repeat center;
}

.layer-popup .layer-icon[type=google_img] {
  background: url(~@/assets/images/basemap/google_img.png) no-repeat center;
}

.layer-popup .layer-popup-title {
  margin-top: 57px;
  width: 80px;
  padding: 4px 0px;
  text-align: center;
  font-size: 11px;
  color: #fff;
  background-color: rgba(0, 0, 0, .5);
}
</style>
